package com.ssy.lingxi.purchase.serviceimpl.tender;

import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.purchase.entity.tender.InviteTenderInCheckRecord;
import com.ssy.lingxi.purchase.repository.tender.InviteTenderInCheckRecordRepository;
import com.ssy.lingxi.purchase.service.tender.IInviteTenderInCheckRecordService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.util.List;

/**
 * 招标实现类
 * @author jw.chen
 * @version 2.0.0
 * @date 2021/3/1
 */
@Service
public class InviteTenderInCheckRecordServiceImpl implements IInviteTenderInCheckRecordService {

    @Resource
    private InviteTenderInCheckRecordRepository inviteTenderInCheckRecordRepository;

    /**
     * 查询招标内部审核记录
     */
    @Override
    public List<InviteTenderInCheckRecord> getInviteTenderInCheckRecord(UserLoginCacheDTO sysUser, Long inviteTenderId){
        return inviteTenderInCheckRecordRepository.findByMemberIdAndMemberRoleIdAndInviteTenderIdOrderByCreateTime(sysUser.getMemberId(), sysUser.getMemberRoleId(), inviteTenderId);
    }

    /**
     * 查询招标内部审核记录--操作日志
     */
    @Override
    public Page<InviteTenderInCheckRecord> getInviteTenderInCheckRecordList(PageVO pageVO, Long inviteTenderId, Long startTime, Long endTime) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return inviteTenderInCheckRecordRepository.findAll(getSpecification(inviteTenderId, startTime, endTime), page);
    }

    /**
     * 构建查询条件
     */
    private Specification<InviteTenderInCheckRecord> getSpecification(Long inviteTenderId, Long startTime, Long endTime){
        return (Specification<InviteTenderInCheckRecord>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            if(inviteTenderId != null && inviteTenderId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("inviteTenderId"), inviteTenderId));
            }

            if(startTime != null && startTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("createTime"), startTime));
            }

            if(endTime != null && endTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("createTime"), endTime));
            }

            //排序
            Order idOrder = criteriaBuilder.desc(root.get("id"));

            return  query.orderBy(idOrder).where(finalConditions).getRestriction();
        };
    }
}

